package com.hw.core.system.service;

import com.hw.core.system.entity.User;
import com.hw.core.system.repository.UserRepository;
import com.hw.core.util.PasswordUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true)//全部方法只读事务
@CacheConfig(cacheNames = "users")
public class UserService {

    @Autowired
    private UserRepository userRepository;


    @Cacheable(key = "'list'")//缓存返回值，下次调用方法体不执行
    public List<User> list() {
        return userRepository.findAll();//

    }

    @Cacheable(key = "#id+'obj'")
    public User getUserById(int id) {
        return userRepository.findOne( id );

    }

    @CacheEvict(allEntries = true)//清除缓存
    @Transactional//事务控制该方法
    public User save(User user) {
        return userRepository.save( user );
    }

    @CacheEvict(allEntries = true)//清除缓存
    @Transactional//事务控制该方法
    public void update(User user) {
        User userById = userRepository.findOne( user.getId() );
        userById.setNickname( user.getNickname() );
        userById.setRole( user.getRole() );
        userById.setGroup( user.getGroup() );
        userById.setLocked( user.getLocked() );
    }

    @Transactional
    @CacheEvict(allEntries = true)//清除缓存
    public void delete(Integer id) {

        userRepository.delete( id );

    }

    @Transactional
    @CacheEvict(allEntries = true)//清除缓存
    public void resetPwd(Integer id) {

        User one = userRepository.findOne( id );
        one.setPassword( PasswordUtil.getPasswordByUsernameAndPassword( one.getName(), "123" ) );

    }

    @Transactional
    @CacheEvict(allEntries = true)//清除缓存
    public void resetPwd2(Integer id, String pwd) {
        User one = userRepository.findOne( id );
        one.setPassword( pwd );
    }

    @CacheEvict(allEntries = true)//清除缓存
    @Transactional//事务控制该方法
    public void resetNickName(Integer id, String nickname) {
        User one = userRepository.findOne( id );
        one.setNickname( nickname );
    }

    @CacheEvict(allEntries = true)//清除缓存
    @Transactional//事务控制该方法
    public void resetImg(Integer id, String img) {
        User one = userRepository.findOne( id );
        one.setImg( img );
    }


}
